package com.example.myapplication

import android.location.Address
import android.location.Geocoder
import androidx.lifecycle.ViewModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers


class MapsViewModel : ViewModel() {
    private var getAddressInfoDisposable: Disposable? = null
    private var getAddressListDisposable: Disposable? = null
    var placesInfoLiveData = SingleLiveEvent<String?>()
    var placesListLiveData = SingleLiveEvent<List<Address>>()
    public fun reqPlacesInfoFromLatlng(geocoder: Geocoder, lat: Double?, lng: Double?) {
        getAddressInfoDisposable?.dispose()

        getAddressInfoDisposable = Observable.fromCallable { getAddressInfo(geocoder, lat, lng) }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                placesInfoLiveData.value = it

            }, { it.printStackTrace() })
    }

    private fun getAddressInfo(geocoder: Geocoder, latitude: Double? = 0.0, longitude: Double? = 0.0): String {
        if (Geocoder.isPresent()) {
            return try {
                val address: List<Address> = geocoder.getFromLocation(latitude!!, longitude!!, 1)
                if (address.isNotEmpty()) {
                    address[0].getAddressLine(0)
                } else {
                    ""
                }
            } catch (e: Exception) {
                e.printStackTrace()
                ""
            }
        }
        return ""
    }

    public fun reqPlacesInfoFromName(geocoder: Geocoder, name: String) {
        getAddressListDisposable?.dispose()
        getAddressListDisposable = Observable.fromCallable { getLocationFromName(geocoder, name) }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                placesListLiveData.value = it
            }, { it.printStackTrace() })
    }

    private fun getLocationFromName(geocoder: Geocoder, name: String): List<Address> {
        if (Geocoder.isPresent()) {
            return try {
                return geocoder.getFromLocationName(name, 5)
            } catch (e: Exception) {
                e.printStackTrace()
                emptyList<Address>()
            }
        }
        return emptyList()
    }


    override fun onCleared() {
        super.onCleared()
        getAddressInfoDisposable?.dispose()
        getAddressListDisposable?.dispose()
    }
}